<template>
  <div class="in-wrap page-wrapper">
    <!-- 公共头 -->
    <header id="header" class="glass-header">
      <section class="container header-container" style="margin-bottom: -10px;margin-top: -50px;">
        <h1 id="logo" style="margin-right: 130px;margin-top: 5px !important;">
          <nuxt-link to="/" title="云启课堂">
            <img src="../assets/img/mysvg/logo.png" width="180" alt="云启课堂" style="margin-top: 8px;height: 45px;"/>
          </nuxt-link>
        </h1>

        <nav class="nav-bar" style="margin-top: 8px !important;">
          <ul class="nav" style="display: inline-block;margin-left: -150px;">
            <nuxt-link to="/" tag="li" active-class="current" exact><a>首页</a></nuxt-link>
            <nuxt-link to="/course" tag="li" active-class="current"><a>课程</a></nuxt-link>
            <nuxt-link to="/teacher" tag="li" active-class="current"><a>讲师</a></nuxt-link>
            <nuxt-link to="/community/article" tag="li" active-class="current"><a>社区</a></nuxt-link>
            <nuxt-link to="/resource" tag="li" active-class="current"><a>智能练习</a></nuxt-link>
            <nuxt-link to="/resource" tag="li" active-class="current"><a>资源</a></nuxt-link>
          </ul>
        </nav>

        <div class="header-right">
          <div class="search-box" style="margin-right: 150px;">
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="请输入关键字..."
            />
            <button @click="handleSearch">
              <!-- <img src="@/assets/img/mysvg/search.png" width="20" height="20" alt="搜索图标" /> -->
              <span>搜索</span>
            </button>
          </div>

          <div>
            <img src="@/assets/img/mysvg/cart.png" width="22" height="22"
                 style="margin-top: 15px !important;margin-right: 15px;">
          </div>
          <div v-if="!userInfo" class="auth-links" style="margin-right: -120px;margin-bottom: -10px;">
            <a href="javascript:void(0)" @click="openLogin" class="btn-login"
               style="color: #66b1ff;margin-right: -10px;">登录</a>
            <span style="font-size: 17px;font-weight: lighter; color: #66b1ff">/</span>
            <a href="javascript:void(0)" @click="openRegister" class="btn-register"
               style="color: #66b1ff;margin-left: -10px;">注册</a>
          </div>

          <div v-else class="user-menu" style="margin-right: -120px;">
            <div style="margin-top: 5px !important;" class="avatar-container"
                 @mouseenter="handleAvatarEnter"
                 @mouseleave="handleAvatarLeave">
              <img :src="safeAvatar" class="avatar" @error="onAvatarError"/>
              <span class="online-dot"></span>
            </div>
            <div class="user-dropdown"
                 @mouseenter="handleDropdownEnter"
                 @mouseleave="handleDropdownLeave"
                 ref="dropdown">
              <div class="user-info">
                <img :src="safeAvatar" class="dropdown-avatar" @error="onAvatarError"/>
                <div>
                  <p class="username">{{ userInfo.username }}</p>
                  <p class="user-role">{{ userInfo.role || '学员' }}</p>
                </div>
              </div>
              <div class="divider"></div>
              <ul>
                <li><a @click.prevent="goToMyCourses"><i class="fa fa-book"></i> 我的课程</a></li>
                <li><a @click.prevent="goToMyArticles"><i class="fa fa-book"></i> 我的文章</a></li>
                <li><a @click.prevent="goToOrderCenter"><i class="fa fa-shopping-cart"></i> 订单中心</a></li>
                <li><a @click.prevent="goToSettings"><i class="fa fa-cog"></i> 个人设置</a></li>
                <div class="divider"></div>
                <li><a @click.prevent="logout" class="logout"><i class="fa fa-sign-out"></i> 退出登录</a></li>
              </ul>
            </div>
          </div>
        </div>
      </section>
    </header>

    <nuxt/>
    <AuthModal ref="authModal"/>
  </div>
</template>

<script>
import '~/assets/css/reset.css'
import '~/assets/css/theme.css'
import '~/assets/css/global.css'
import '~/assets/css/web.css'
import '~/assets/css/myset.css'
import AuthModal from '@/components/AuthModal.vue'
import {isTokenExpired} from "@/utils/jwt";

export default {
  components: {AuthModal},
  data() {
    return {
      defaultAvatar: require('~/assets/img/avatar-boy.gif'),
      searchKeyword: '',
      navItems: [
        {path: '/', title: '首页', icon: 'fa-home'},
        {path: '/course', title: '课程', icon: 'fa-book'},
        {path: '/teacher', title: '讲师', icon: 'fa-user'},
        {path: '/community/article', title: '社区', icon: 'fa-file-text'},
        {path: '/resource', title: '资源', icon: 'fa-question-circle'}
      ],
      dropdownTimer: null,
      isHoveringAvatar: false,
      isHoveringDropdown: false
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo || null
    },
    safeAvatar() {
      if (!this.userInfo?.avatar) return this.defaultAvatar
      let avatar = this.userInfo.avatar
      if (avatar.startsWith('http://') && location.protocol === 'https:') {
        avatar = avatar.replace('http://', 'https://')
      }
      return avatar || this.defaultAvatar
    },
  },

  mounted() {
    const token = localStorage.getItem('token');
    const userInfoStr = localStorage.getItem('userInfo');

    if (token) {
      if (isTokenExpired(token)) {
        // token过期，清理状态
        this.$store.commit('setToken', null);
        this.$store.commit('setUserInfo', null);
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        this.$router.push('/');
        return;
      }
      this.$store.commit('setToken', token);

      if (userInfoStr) {
        try {
          this.$store.commit('setUserInfo', JSON.parse(userInfoStr));
        } catch (e) {
          console.error('userInfo parse error:', e);
          this.$store.commit('setUserInfo', null);
        }
      } else {
        this.$store.commit('setUserInfo', null);
      }
    } else {
      this.$store.commit('setToken', null);
      this.$store.commit('setUserInfo', null);
      this.$router.push('/login');
      return;
    }

    window.addEventListener('scroll', this.handleScroll);
    this.handleScroll();
  },

  methods: {
    openLogin() {
      this.$refs.authModal.show('account')
    },
    openRegister() {
      this.$refs.authModal.show('register')
    },
    async logout() {
      await this.$store.dispatch('logout')
      this.$router.push('/')
    },
    onAvatarError(e) {
      e.target.src = this.defaultAvatar
    },
    handleSearch() {
      if (this.searchKeyword.trim()) {
        this.$router.push({path: '/search', query: {keyword: this.searchKeyword.trim()}})
      }
    },
    goToMyCourses() {
      this.$router.push('/user/courses')
    },
    goToMyArticles() {
      this.$router.push('/user/articles')
    },
    goToOrderCenter() {
      this.$router.push('/user/orders')
    },
    goToSettings() {
      this.$router.push('/user/settings')
    },
    handleScroll() {
      const header = document.getElementById('header')
      if (window.scrollY > 50) {
        header.classList.add('scrolled')
      } else {
        header.classList.remove('scrolled')
      }
    },
    showDropdown() {
      clearTimeout(this.dropdownTimer)
      this.$refs.dropdown.style.display = 'block'
      setTimeout(() => {
        this.$refs.dropdown.style.opacity = '1'
        this.$refs.dropdown.style.transform = 'scale(1)'
        this.$refs.dropdown.style.pointerEvents = 'auto'
      }, 10)
    },
    hideDropdown() {
      this.dropdownTimer = setTimeout(() => {
        // 只有当鼠标不在头像区域且不在下拉菜单区域时才关闭
        if (!this.isHoveringAvatar && !this.isHoveringDropdown) {
          this.$refs.dropdown.style.opacity = '0'
          this.$refs.dropdown.style.transform = 'scale(0.95)'
          this.$refs.dropdown.style.pointerEvents = 'none'
          setTimeout(() => {
            this.$refs.dropdown.style.display = 'none'
          }, 300)
        }
      }, 200)
    },
    handleAvatarEnter() {
      this.isHoveringAvatar = true
      this.showDropdown()
    },
    handleAvatarLeave() {
      this.isHoveringAvatar = false
      this.hideDropdown()
    },
    handleDropdownEnter() {
      this.isHoveringDropdown = true
      this.showDropdown()
    },
    handleDropdownLeave() {
      this.isHoveringDropdown = false
      this.hideDropdown()
    }
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
}
</script>

<style scoped>
html {
  overflow-y: scroll !important;
}

.page-wrapper {
  min-height: calc(100vh - 100px) !important;
}
</style>
